<template>
  <div class="container">
    <van-sticky>
      <div class="head">
        <img class="head-back-img" @click="goBack" src="../assets/back.svg" alt="">
        <div class="title">兑换订单</div>
      </div>
    </van-sticky>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="订单已全部加载完毕" @load="onLoads">
        <div class="list" v-for="(item, index) in list" :key="index" @click="goDetail(item)">
          <div class="header">
            <div>
              <div>
                <span>订单编号：{{ item.outTradeNo }}</span>
              </div>
              <div>{{ item.status }}</div>
            </div>
          </div>
          <div class="con">
            <div class="left">
              <img :src="item.productPath" alt="">
              <div>
                <div>
                  <span>{{ item.productName }}</span>
                </div>
                <div>
                  <div>充值号码：{{ item.rechargeNumber }}</div>
                  <div>开始时间：{{ item.startTime }}</div>
                  <div>结束时间：{{ item.endTime }}</div>
                </div>
              </div>
            </div>
            <div class="right">
              <div>
                <span>¥</span>
                <span>{{ item.officialPrice }}</span>
              </div>
            </div>
            <!-- <div v-if="item.status === '订单完成'" class="right">已完成</div> -->
            <!--          <div class="right" v-if="item.status === '出票中' && item.isRefund === 1">申请退款</div>-->
          </div>
          <div class="money">
            <div>
              <span> 实付款</span>
              <span> ¥</span>
              <span>{{ item.wxOrderAmount || 0 }}</span>
            </div>
            <!--          <div>共{{ item.ticketNum }}张</div>-->
          </div>
          <div class="fot">
            <!--                实付款：{{item.clientMarketAmount}}元-->
            <div></div>
            <div>
              <div v-if="item.status === '待支付'" class="goPays" @click.stop="handleUnlock(item)">取消订单</div>
              <div v-if="item.status === '待支付'" class="goPay" @click.stop="handleGoPay(item)">去支付</div>
              <!-- <div v-if="item.status === '出票成功'" class="goPay" @click.stop="getCode(item)">取票</div> -->
              <!-- <div v-if="item.status === '订单完成'" class="rightBtn">评价</div> -->
              <!-- <div class="rightBtn" v-if="item.status === '出票中' && item.isRefund === 1">申请退款</div> -->
              <!-- <div
              v-if="item.status === '出票中' && item.isRefund === 1 || item.status === '出票成功' && item.isRefund === 1 || item.status === '出票失败' && item.isRefund === 1"
              class="goPay">申请退款</div> -->
            </div>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>
    <van-overlay :show="show" @click="show = false">
      <div class="wrapper">
        <div class="block">
          <div>
            <span>取票核销码</span>
            <img @click="show = false" src="../assets/order/close.svg" alt="二维码" />
          </div>
          <div>{{ detailObj.ticketContentTips }}</div>
          <div>
            <div v-for="(image, index) in codeList" :key="index" class="qr-item">
              <img v-if="image.imgUrl" :src="image.imgUrl" alt="取票码二维码" />
              <div class="seat-info">{{ image.text }}</div>
              <div v-if="image.verificationCode" class="verification-code">
                验证码: {{ image.verificationCode }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </van-overlay>
  </div>
</template>
<script>
import plantAPI from "@/api/plant";
import { Toast, Dialog } from "vant";
import QRCode from "qrcode";
export default {
  data() {
    return {
      show: false,
      list: [
        // {
        //   consumeAmount:100,
        //   endTime:'2022-12-12 12:12',
        //   officialPrice:'展示价',
        //   orderNo:'111111',
        //   rechargeNumber:'13525625689',
        //   startTime:'2022-12-12 12:12',
        //   status:'订单完成',
        //   wxOrderAmount:0,
        //   img:'../assets/1.jpg',
        //   name:'爱奇艺'
        // }
      ],
      loading: false,
      finished: false,
      pageNum: 1,
      pageSize: 10,
      codeList: [],
      detailObj: {},
      isLoading: false
    }
  },
  methods: {
    handleUnlock(item) {
      Dialog.confirm({
        message: '确定要取消此订单吗？'
      })
        .then(() => {
          plantAPI.ordernlockAPI(item.outTradeNo).then(res => {
            Toast.success('取消成功');
            this.pageNum = 1;
            this.list = [];
            this.initData()

          })
        })
        .catch(() => {
          // on cancel
        });

    },
    onRefresh() {
      setTimeout(() => {
        this.pageNum = 1;
        this.list = []
        this.initData()
        this.isLoading = false;
      }, 1000);
    },
    parseTicketCodes(input, seats) {
      if (!input || typeof input !== 'string') return [];
      const trimmedInput = input.trim();
      if (!trimmedInput) return [];

      // 分割座位信息
      const seatArray = seats ? seats.split(/[,，]/).map(s => s.trim()) : [];

      const codeSegments = trimmedInput.split(/[,，]/).map(s => s.trim()).filter(Boolean);
      return codeSegments.map((segment, index) => {
        const separator = segment.includes('|') ? '|' : (segment.includes('｜') ? '｜' : null);
        const seatText = seatArray[index] || '';

        if (separator) {
          const [ticketCode, verificationCode] = segment.split(separator);
          return {
            ticketCode: ticketCode.trim(),
            verificationCode: verificationCode.trim() || null,
            text: seatText  // 添加座位信息
          };
        }

        return {
          ticketCode: segment,
          verificationCode: null,
          text: seatText  // 添加座位信息
        };
      });
    },
    async getCode(item) {
      try {
        const res = await plantAPI.getunorderAPI(item.orderNo);
        this.detailObj = res.data;
        this.newSeatName = this.detailObj.seatNames.replace(/\|/g, '  ');

        if (this.detailObj) {
          this.codeList = this.parseTicketCodes(
            this.detailObj.ticketContent,
            this.detailObj.seatNames
          );
          for (let item of this.codeList) {
            if (item.verificationCode) {
              try {
                item.imgUrl = await this.generateQRCode(item.verificationCode);
              } catch (e) {
                item.imgUrl = '';
              }
            }
          }

          this.show = true;
        }
      } catch (error) {
        Toast.fail('获取订单详情失败');
      }
    },
    async generateQRCode(qrData) {
      try {
        // 生成二维码并转换为 Data URL
        const qrImageUrl = await QRCode.toDataURL(qrData, {
          width: 200,          // 宽度
          margin: 2,           // 边距
          errorCorrectionLevel: "H",
        });
        return qrImageUrl
      } catch (err) {
      }
    },
    checkTimeWithin10Minutes(targetTimeStr) {
      // 1. 将目标时间字符串转换为 Date 对象
      const targetTime = new Date(targetTimeStr);

      // 2. 计算目标时间 + 10 分钟后的时间
      const targetTimePlus10Min = new Date(targetTime.getTime() + 10 * 60 * 1000);

      // 3. 获取当前时间
      const now = new Date();
      // 4. 判断是否超过 10 分钟
      if (now > targetTimePlus10Min) {
        return 0; // 超过 10 分钟
      } else {
        return targetTimePlus10Min - now; // 返回剩余毫秒数
      }
    },
    handleGoPay(item) {
      // this.$router.push({
      //   path: '/welfarePay/',
      //   query: {
      //     productNo: item.productNo,
      //     imgs: item.pic,
      //     rechargeNumber: item.rechargeNumber
      //   }
      // })

      sessionStorage.setItem(
        'welfarePayData',
        JSON.stringify({
          productNo: item.productNo,
          imgs: item.pic,
          showPrice: item.officialPrice,
          rechargeNumber: item.rechargeNumber
        })
      );

      // 只带一个极短标识（没有也行）跳转到支付页
      window.location.replace(`https://xhjzh.life/welfarePay/?productNo=${item.productNo}`);
    },
    goBack() {
      this.$router.push(
        {
          path: '/user'
        }
      )
    },
    goDetail(item) {
      this.$router.push(
        {
          path: '/cardUsageRecordDetail',
          query: {
            orderNo: item.outTradeNo
          }
        }
      )
    },
    onLoads() {
      this.initData()
    },
    initData() {
      this.loading = true;
      plantAPI.convertList({
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(async res => {
        const result = res.rows;
        result.forEach(item => {
          this.list.push(item);
        });
        this.loading = false;
        if (this.list.length !== res.total) {
          this.finished = false;
          this.pageNum++;
        } else {
          this.finished = true;
        }
      });
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .van-sticky {
  background: #FFFFFF;

}

::v-deep .van-pull-refresh {
  // height: calc(100vh - 50px);
}

.container {
  min-height: 100vh;
  background: rgb(244, 244, 244);

  .head {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    position: relative; // 关键：设置相对定位
    background-color: #ffffff;

    .head-back-img {
      width: 20px;
      height: 20px;
      position: absolute;
      left: 15px;
    }

    .title {
      width: 100%;
      text-align: center;
      font-size: 16px;
      color: #000000;
    }
  }

  .list {
    width: 100%;
    background: #ffffff;
    margin-top: 8px;
    border-top: 1px solid #eeeeee;
    border-bottom: 1px solid #eeeeee;

    .header {
      width: 100%;
      padding: 0 20px;
      box-sizing: border-box;

      >div {
        width: 100%;
        height: 40px;
        line-height: 40px;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #5B626A;
        font-size: 12px;
        border-bottom: 1px solid #eeeeee;

        >div:nth-child(1) {
          display: flex;
          align-items: center;

          img {
            width: 15px;
            height: 15px;
          }
        }

        >div:nth-child(2) {
          color: rgb(255, 89, 122);
        }
      }

    }

    .con {
      width: 100%;
      padding: 10px 20px 5px 20px;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      //align-items: center;

      .left {
        width: calc(100% - 84px);
        display: flex;
        justify-content: space-between;
        //align-items: center;

        >img {
          width: 80px;
          height: 80px;
          border-radius: 8px;
        }

        >div {
          width: calc(100% - 75px);
          //height: 100px;
          display: flex;
          margin-left: 15px;
          flex-wrap: wrap;
          align-content: space-between;

          >div:nth-child(1) {
            width: 100%;
            color: #1e1d1e;
            font-size: 14px;
            font-weight: bold;
            //white-space: nowrap;
            //text-overflow: ellipsis;
            //overflow: hidden;
          }

          >div:nth-child(2) {
            width: 100%;

            >div {
              width: 100%;
              color: #525152;
              font-size: 12px;
              white-space: nowrap;
              text-overflow: ellipsis;
              overflow: hidden;
              margin-top: 6px;
            }

            >div:nth-child(2),
            >div:nth-child(3) {
              color: #8f8e8f;
            }
          }
        }

      }

      .right {
        width: 64px;
        display: flex;
        justify-content: flex-end;

        >div {
          text-align: right;
          display: flex;
          align-content: space-between;
          margin-top: 10px;

          span {
            font-size: 12px;
            font-weight: bold;

          }

          >span:nth-child(1) {
            margin-top: 1px;
            font-size: 11px;
            margin-right: 1px;
          }
        }
      }
    }

    .money {
      width: 100%;
      padding: 0 20px;
      box-sizing: border-box;
      display: flex;
      flex-direction: row-reverse;
      align-items: center;
      margin-top: 4px;

      >div {
        color: #000000;
        font-size: 12px;

        >span:nth-child(2) {
          margin: 0 1px 0 3px;
        }

        >span:nth-child(3) {
          font-size: 16px;
          font-weight: bold;
        }
      }

      >div:nth-child(2) {
        color: #5e5c5c;
        font-size: 12px;
        margin-right: 10px;
      }
    }

    .fot {
      width: 100%;
      padding: 10px 15px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #8f8e8f;
      font-size: 12px;

      >div:nth-child(2) {
        display: flex;

        >div {
          border: 1px solid #8f8e8f;
          width: 64px;
          height: 26px;
          line-height: 26px;
          text-align: center;
          border-radius: 17px;
        }

        .goPay {
          border: 1px solid rgb(255, 89, 122);
          color: rgb(255, 89, 122);
          margin-right: 10px;
        }

        .goPays {
          border: 1px solid #999;
          color: #999;
          margin-right: 10px;
        }

        .rightBtn {
          width: 64px;
          height: 26px;
          line-height: 26px;
          border-radius: 17px;
          background-color: rgba(246, 57, 13, 1);
          color: #FFFFFF;
          font-size: 12px;
          text-align: center;
          border: 1px solid rgba(246, 57, 13, 1);
        }
      }

    }
  }
}


.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.block {
  width: 300px;
  //height: 300px;
  background-color: #fff;
  border-radius: 15px;
  padding: 7px 13px;
  box-sizing: border-box;

  >div:nth-child(1) {
    color: rgba(16, 16, 16, 1);
    font-size: 18px;
    font-weight: bold;
    width: 100%;
    display: flex;
    justify-content: space-between;

    img {
      width: 22px;
      height: 29px;
    }

  }

  >div:nth-child(2) {
    color: rgba(154, 154, 154, 1);
    font-size: 14px;
    margin-top: 5px;
    width: 100%;
    text-align: left;
  }

  >div:nth-child(3) {
    width: 143px;
    height: 180px;
    margin: 25px auto 25px;

    .van-swipe {
      width: 150px;
      height: 170px;
      margin: auto;
    }

    .van-swipe-item {
      display: flex;
      flex-wrap: wrap;

      img {
        width: 150px;
        height: 150px;
      }

      >div {
        width: 100%;
        height: 20px;
        line-height: 20px;
        font-size: 14px;
        font-weight: bold;
        text-align: center;
      }
    }
  }
}

.qr-item {
  text-align: center;

  img {
    width: 150px;
    height: 150px;
    display: block;
    margin: 0 auto;
  }

  .seat-info {
    margin-top: 5px;
    font-size: 14px;
    font-weight: bold;
    color: #333;
  }

  .verification-code {
    margin-top: 5px;
    padding-bottom: 10px;
    font-size: 12px;
    color: #666;
  }
}
</style>
